﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>职称设置</title>
    <script src="~/lib/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css">
    <script src="//unpkg.com/element-plus"></script>
    <style>
        body {
            background-color: #FFFFCC;
        }

        .solid-table {
            border-collapse: collapse;
            width: 100%;
        }

            .solid-table td {
                border: 1px solid #333;
                padding: 8px;
                text-align: left;
            }

        .bj {
            background-color: #FFD553;
        }

        .kuan {
            width: 240px;
        }

        .input-error {
            border: 2px solid #f56c6c !important;
            box-shadow: 0 0 5px rgba(245, 108, 108, 0.5);
        }

        .error-message {
            color: #f56c6c;
            font-size: 12px;
            margin-top: 2px;
            display: none;
        }

            .error-message.show {
                display: block;
            }

        .timer {
            display: inline-block;
            margin-left: 10px;
            color: #f56c6c;
            font-weight: bold;
        }

        /* 新增：错误提示容器样式 */
        .form-group {
            position: relative;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="content-container">
            <div class="header">
                <div class="breadcrumb">您正在做的业务是：人力资源--薪酬标准管理--薪酬标准登记</div>
                <el-button type="primary" v-on:click="goToAddPage">添加</el-button>
                <el-button type="primary" onclick="history.back()">返回</el-button>
            </div>
            <table class="solid-table">
                <tr>
                    <td class="bj">薪酬标准编号</td>
                    <td class="kuan">
                        <div class="form-group">
                            <input style="width:100%" v-model="Dig" readonly="readonly" />
                            <div class="error-message" v-if="errors.Dig">不能为空</div>
                        </div>
                    </td>
                    <td class="bj">薪酬标准名称</td>
                    <td class="kuan">
                        <div class="form-group">
                            <input style="width:100%" v-model="xc_name" v-on:blur ="validateField('xc_name', xc_name)" :class="{'input-error': errors.xc_name}" />
                            <div class="error-message" v-if="errors.xc_name">不能为空</div>
                        </div>
                    </td>
                    <td class="bj">薪酬总额</td>
                    <td class="kuan">
                        <div class="form-group">
                            <input style="width:100%" v-model="ze" v-on:blur="validateField('ze', ze)" :class="{'input-error': errors.ze}" />
                            <div class="error-message" v-if="errors.ze">不能为空</div>
                        </div>
                    </td>
                    <td class="bj"></td>
                </tr>
                <tr>
                    <td class="bj">制定人</td>
                    <td class="kuan">
                        <div class="form-group">
                            <select v-model="zdr" style="width:223.2px;height:30px" v-on:blur="validateField('zdr', zdr)" :class="{'input-error': errors.zdr}">
                                @foreach (var item in ViewBag.zhi2)
                                {
                                    <option>@item.u_true_name</option>
                                }
                            </select>
                            @* <input style="width:100%" v-model="zdr" v-on:blur="validateField('zdr', zdr)"  /> *@
                            <div class="error-message" v-if="errors.zdr">不能为空</div>
                        </div>
                    </td>
                    <td class="bj">登记人</td>
                    <td class="kuan">
                        <div class="form-group">
                            <input style="width:100%" v-model="djr" readonly="readonly" v-on:blur="validateField('djr', djr)" :class="{'input-error': errors.djr}" />
                            <div class="error-message" v-if="errors.djr">不能为空</div>
                        </div>
                    </td>
                    <td class="bj">登记时间</td>
                    <td class="kuan">
                        <div class="form-group">
                            <input style="width:calc(100%); display: inline-block;" v-model="djsj" v-on:blur="validateField('djsj', djsj)" :class="{'input-error': errors.djsj}" />
                            <div class="error-message" v-if="errors.djsj">不能为空</div>
                        </div>
                    </td>
                    <td class="bj"></td>
                </tr>
                <tr>
                    <td class="bj">备注</td>
                    <td colspan="6">
                        <div class="form-group">
                            <textarea style="width:100%" v-model="bz" v-on:blur="validateField('bz', bz)" :class="{'input-error': errors.bz}"></textarea>
                            <div class="error-message" v-if="errors.bz">不能为空</div>
                        </div>
                    </td>
                </tr>
            </table>
            <table v-if="tableData1.length" class="solid-table" style="border-top: none;">
                <thead>
                    <tr>
                        <td class="bj" style="width:137.93px;border-top: none;">序号</td>
                        <td class="bj" style="width:377.93px;border-top: none;">薪酬项目名称</td>
                        <td class="bj" style="border-top: none;">金额</td>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="item in tableData1" :key="item.id">
                        <td>{{ item.id }}</td>
                        <td>{{ item.name }}</td>
                        <td>
                            <div class="form-group">
                                <input v-model.number="item.value" :name="item.id" v-on:input="jd" v-on:blur="validateAmount(item)" :class="{'input-error': errors[`amount_${item.id}`]}" />
                                <div class="error-message" v-if="errors[`amount_${item.id}`]">金额不能为空</div>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
            <p v-else class="mt-4 text-gray-500">未选择任何项目</p>
            <!-- 新增的项目选择和动态表格区域 -->
            <div>
                <div class="mb-4">
                    <label>选择项目：</label>
                    <!-- 修改复选框绑定，使用item.selected属性表示选中状态 -->
                    <div v-if="projectOptions.length" class="d-flex flex-wrap">
                        <label v-for="item in projectOptions" :key="item.id" class="ml-2">
                            <input type="checkbox" v-model="item.selected" :value="item.group_id" />{{ item.group_name }}
                        </label>
                    </div>
                </div>
                @* <div class="mb-4">
                    <label>选择项目：</label>

                    <label class="ml-2"><input type="checkbox" v-model="selectedIds" value="1">出差补助</label>
                    <label class="ml-2"><input type="checkbox" v-model="selectedIds" value="2">交通补贴</label>
                    <label class="ml-2"><input type="checkbox" v-model="selectedIds" value="3">住房补贴</label>
                    <label class="ml-2"><input type="checkbox" v-model="selectedIds" value="4">基本工资</label>
                    <label class="ml-2"><input type="checkbox" v-model="selectedIds" value="5">年终奖</label>
                    <label class="ml-2"><input type="checkbox" v-model="selectedIds" value="6">误餐补助</label>
                </div> *@
                <el-button v-on:click="generateTable">
                    生成表格
                </el-button>
                <!-- 动态表格 -->

            </div>
        </div>
    </div>

    <script>
        // 格式化日期时间为YYYY-MM-DD HH:MM:SS格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        // 格式化计时器显示
        function formatTimer(seconds) {
            const h = Math.floor(seconds / 3600);
            const m = Math.floor((seconds % 3600) / 60);
            const s = seconds % 60;

            return [
                h.toString().padStart(2, '0'),
                m.toString().padStart(2, '0'),
                s.toString().padStart(2, '0')
            ].join(':');
        }

        const { createApp, ref, reactive } = Vue;

        const app = createApp({
            setup() {
                const tableData = ref([]);
                const projectOptions = ref([]);
                const ze = ref(0.00);
                const ze1 = ref(0.00);
                const Dig = ref();
                const ze_name = ref();
                const xc_name = ref();
                const zdr = ref();
                const djr = ref("@Context.Session.GetString("UPName")"); // 示例值，实际应从会话获取
                // 修改为精确到秒的格式
                const djsj = ref(formatDateTime(new Date()));
                const bz = ref();

                // 新增：错误状态管理
                const errors = reactive({
                    xc_name: false,
                    ze: false,
                    zdr: false,
                    djr: false,
                    djsj: false,
                    bz: false
                });

                // 新增：项目选择和动态表格相关数据
                const selectedIds = ref([]);
                const tableData1 = ref([]);

                // 计时器相关变量
                const isTimerRunning = ref(true); // 默认自动开始计时
                let timerInterval = null;
                let startTime = null;
                let elapsedTime = 0;

                // 开始计时器
                const startTimer = () => {
                    startTime = new Date().getTime() - elapsedTime;
                    timerInterval = setInterval(() => {
                        const currentTime = new Date().getTime();
                        elapsedTime = currentTime - startTime;
                        const seconds = Math.floor(elapsedTime / 1000);

                        // 同时更新djsj的值为当前精确时间
                        djsj.value = formatDateTime(new Date());
                    }, 1000);
                    isTimerRunning.value = true;
                };


                function jd(event) {
                    //calculateTotal();

                    // 保留原有逻辑（可选）
                    const currentValue = parseFloat(event.target.value) || 0;
                    const previousTotal = parseFloat(ze.value) || 0;
                    if(currentValue != 0 && event.srcElement.name != ze_name.value){
                        ze.value = (previousTotal + currentValue).toFixed(2);
                    }else if(event.srcElement.name == ze_name.value){
                        ze.value = (previousTotal - ze1.value + currentValue).toFixed(2);
                    }
                    ze1.value = currentValue;
                    ze_name.value = event.srcElement.name;
                    console.info("当前值:", currentValue, "总计:", ze.value);
                }

                // 验证单个字段
                const validateField = (fieldName, fieldValue) => {
                    // 重置之前的错误状态
                    errors[fieldName] = false;
                    console.info(fieldName+"a"+fieldValue);

                    // 检查是否为空
                    if (!fieldValue || fieldValue === undefined) {
                        errors[fieldName] = true;
                    }
                };

                // 验证金额字段
                const validateAmount = (item) => {
                    const fieldName = `amount_${item.id}`;
                    errors[fieldName] = false;

                    if (item.value === undefined || item.value === null || item.value.toString().trim() === '') {
                        errors[fieldName] = true;
                    }
                };

                const generateTable = () => {
                    ze.value = 0;

                    // 1. 准确筛选出被选中的项目（通过selected属性判断）
                    const selectedProjects = projectOptions.value.filter(item => item.selected);

                    // 2. 清空现有表格数据
                    tableData1.value = [];

                    // 3. 根据选中的项目生成表格数据
                    if (selectedProjects.length > 0) {
                        selectedProjects.forEach((item, index) => {
                            tableData1.value.push({
                                id: index + 1,
                                name: item.group_name,
                                value: 0
                            });
                        });
                    }
                };

                let counter = 0;

                function Digits() {
                    // const array = new Uint32Array(1);
                    // window.crypto.getRandomValues(array);
                    // const randomNumber = array[0] % Math.pow(10, 10);
                    // return randomNumber.toString().padStart(10, '0');
                    const timestamp = Math.floor(Date.now() / 1000);
                    // 取时间戳的后8位
                    const timestampPart = timestamp.toString().slice(-8);

                    // 同一秒内使用计数器（0-99）
                    counter = (counter + 1) % 100;
                    const counterPart = counter.toString().padStart(2, '0');

                    // 组合成10位数字
                    return timestampPart + counterPart;
                }

                function fill() {
                    Dig.value = "135" + Digits();
                    axios.get(`/SS_Insert/Index2`)
                      .then(res => {
                          console.info(res.data);
                          // 为每个项目添加selected属性，初始值为false
                          projectOptions.value = res.data.zhi.map(item => ({
                              ...item,
                              selected: false
                          }));
                      }).catch(err => {
                          console.info(err)
                      })
                }

                const goToAddPage = () => {
                    // 验证所有必填字段
                    validateField('xc_name', xc_name);
                    validateField('ze', ze);
                    validateField('zdr', zdr);
                    validateField('djr', djr);
                    validateField('djsj', djsj);
                    validateField('bz', bz);

                    // 验证表格中的金额字段
                    tableData1.value.forEach(item => {
                        validateAmount(item);
                    });

                    // 检查是否有错误
                    const hasErrors = Object.values(errors).some(error => error);
                    if (hasErrors) {
                        ElementPlus.ElMessage.error('请填写所有必填字段');
                        return;
                    }

                    ElementPlus.ElMessageBox.confirm(
                        `确定添加吗？`,
                        '添加确认',
                        {
                            confirmButtonText: '确认添加',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }
                    )
                    .then(() => {
                        insertTitle();
                    })
                    .catch(() => {
                        ElementPlus.ElMessage.info('已取消添加');
                    });
                };

                function insertTitle() {
                    if(xc_name.value === undefined || ze.value === undefined || djr.value === undefined || djsj.value === undefined || bz.value === undefined ){
                        ElementPlus.ElMessage.error('不能为空');
                        return null;
                    }
                    // if(djsj.value == undefined || djsj.value === ''){
                    //     djsj.value = new Date().toISOString().split('T')[0]; 使用当前日期
                    // }

                    // 准备额外项目数据
                    const extraItems = tableData1.value.map(item => ({
                        id: item.id,
                        name: item.name,
                        value: item.value
                    }));
                    axios.post(`/SS_Insert/insert`, null, {
                        params: {
                            Dig: Dig.value,
                            XC_name: xc_name.value,
                            ZE: ze.value,
                            ZDR: zdr.value,
                            DJR: djr.value,
                            DJSJ: new Date(djsj.value).toISOString(),
                            BZ: bz.value,
                            // 注意：实际项目中可能需要调整参数格式
                            // 这里只是示例，可能需要将extraItems序列化为JSON字符串
                            extraItems: JSON.stringify(extraItems)
                        }
                    })
                    .then(res => {
                        console.info(res.data);
                        if(res.data.fh > 0){
                            ElementPlus.ElMessage.success('添加成功');
                        }else{
                            ElementPlus.ElMessage.error('添加失败，请重试');
                        }
                    })
                    .catch(err => {
                        console.info(err);
                        ElementPlus.ElMessage.error('网络错误，请重试');
                    });
                }

                fill();

                // 初始化
                Vue.onMounted(() => {
                    // 初始更新一次时间
                    djsj.value = formatDateTime(new Date());
                    // 自动开始计时
                    startTimer();
                });

                // 组件卸载时清理计时器
                Vue.onUnmounted(() => {
                    if (timerInterval) {
                        clearInterval(timerInterval);
                    }
                });

                return {
                    tableData,
                    goToAddPage,
                    jd,
                    ze,
                    Dig,
                    xc_name,
                    zdr,
                    djr,
                    djsj,
                    bz,
                    errors,
                    validateField,
                    validateAmount,
                    // 新增返回值
                    selectedIds,
                    tableData1,
                    generateTable,
                    isTimerRunning,
                    projectOptions
                }
            }
        });

        app.use(ElementPlus);
        app.mount('#app');
    </script>
</body>
</html>